'use strict';

/*global.models = {};
// 测试环境之用
global.client_id = '3799249803934DE99495C9584AE68449';
global.client_secret = 'F07B8035741F42D7A0D7F6F71F98CB1A';

var express = require('express')
  , logs = require('../conf/logs')
  , config = require('../conf/config')
  , settings = require('../conf/settings')
  , path = require('path')
  , http = require('http')
  , https = require('https')
  , fs = require('fs')
  , async = require("async");*/


var _ = require('underscore');
var CronJob = require('cron').CronJob;
var moment = require('moment');
var db = require('../conf/db.js');
var config = require('../conf/config');
var remoteRequest = require('../components/util/remoteRequest');


var msgRemind = function(){
    
    var start = function(){
        // 获取前一天时间精确到日
        var yesterday = moment().add(-1, 'day');
        var hours = ' 00:00:00';
        var start = new Date(yesterday.format('DD-MM-YYYY') + hours);
        var end = new Date(moment().format('DD-MM-YYYY') + hours);
        var timeScope = {start : start, end : end};

        // 查询
        var  models = db.models('SignIn');
        _.each(models, function(model){
            queryErrorSignIn(model, timeScope);
        });

    };

    var queryErrorSignIn = function(signInModel, scope){
        signInModel.aggregate([
            {$match: {"signInTime": { $gte: scope.start, $lt : scope.end}, count : 1}},
        ]).group({_id : {
                "year": { "$year": "$signInTime" },
                "day": { "$dayOfYear": "$signInTime" }
            }, signIn : {$push: "$$ROOT"}, count: { $sum: 1 }})
        .exec(function(err, datas){
            console.info(datas);
            if (err) {
                console.error('异常信息为：%s', JSON.stringify(err));
            } else {
                _.each(datas, function(data){
                    var signInObj = data.signIn[0];
                    msgSend(signInObj);
                    signInObj.isPass = false;
                    signInObj.save();
                });
            }
        });
    };

    var msgSend = function(signIn){
        var params = {
                users   :   [signIn.userId],
                msgBody :   [{
                    'description' : '您昨天只打了一次卡！',
                    'picUrl': config.remote[config.currEvn].msgImgUrl,
                    'title': '异常打卡提醒',
                    'url': config.remote[config.currEvn].msgDetailUrl + signIn._id
                }]
        };
        remoteRequest.sendMsg(params);
    }; 
    
    return {
        start : start
    };
}();

msgRemind.start();

module.exports = function(){
	    var msgRemindJob = new CronJob({
        cronTime: '0 0 1 * * *',
        onTick: function() {
            console.info("%s:定时消息发送轮训扫描开始", moment().format('YYYY-MM-DD HH:mm:ss'));

            try {
                msgRemind.start();
            } catch(err) {
                console.error('定时消息轮训任务发生异常：%s', JSON.stringify(err));
            }
        },
        start: false
    });
};

